package com.example.demo.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.bean.NfcBind;
import com.example.demo.bean.PageConfig;
import com.example.demo.mapper.NfcBindMapper;
import com.example.demo.mapper.PageConfigMapper;
import com.example.demo.service.NfcBindService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.example.demo.vo.NfcVo;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class NfcBindServiceImpl extends ServiceImpl<NfcBindMapper, NfcBind> implements NfcBindService {


    private final NfcBindMapper bindMapper;
    private final PageConfigMapper configMapper;


    @Override
    public List<PageConfig> dropdown() {
        return configMapper.selectList(Wrappers.<PageConfig>lambdaQuery()
                .select(PageConfig::getId, PageConfig::getTitle));
    }

    @Override
    public void bind(String nfcId, Integer pageId) {
// 1. NFC 已存在 → 更新；不存在 → 新增
        NfcBind one = bindMapper.selectOne(
                Wrappers.<NfcBind>lambdaQuery().eq(NfcBind::getNfcId, nfcId));
        if (one == null) {
            one = new NfcBind();
            one.setNfcId(nfcId);
        }
        one.setPageId(pageId);
        one.setBindTime(LocalDateTime.now());
        bindMapper.insert(one); // MP 提供的存在即更新
    }

    @Override
    public void unbind(String nfcId) {
        bindMapper.delete(Wrappers.<NfcBind>lambdaQuery().eq(NfcBind::getNfcId, nfcId));
    }

    @Override
    public PageConfig getPageByNfc(String nfcId) {
        NfcBind bind = bindMapper.selectOne(
                Wrappers.<NfcBind>lambdaQuery().eq(NfcBind::getNfcId, nfcId));
        return bind == null ? null : configMapper.selectById(bind.getPageId());
    }

    @Override
    public List<NfcVo> listAll() {
        return bindMapper.selectListWithTitle();
    }
}
